package com.audaque.springboot.foshanupload.core.util;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;


/**
 * @author Jin
 * @date 2021/11/1
 */
@Slf4j
public class IpUtil {

    /**
     * 获取当前服务器的IP地址(内网)
     */
    public static String getHostAddress() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            return address.getHostAddress();
        } catch (Exception e) {
            return "未知";
        }
    }

    /**
     * 获取当前服务器的IP地址(内网)
     */
    public static String getInet4Address() {
        try {
            //获取所有网络接口
            Enumeration<NetworkInterface> allNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
            //遍历所有网络接口
            for (; allNetworkInterfaces.hasMoreElements(); ) {
                NetworkInterface networkInterface = allNetworkInterfaces.nextElement();
                //如果此网络接口为 回环接口 或者 虚拟接口(子接口) 或者 未启用 或者 描述中包含VM
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp() || networkInterface.getDisplayName().contains("VM")) {
                    //继续下次循环
                    continue;
                }
                //遍历此接口下的所有IP（因为包括子网掩码各种信息）
                for (Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses(); inetAddressEnumeration.hasMoreElements(); ) {
                    InetAddress inetAddress = inetAddressEnumeration.nextElement();
                    //如果此IP不为空
                    if (inetAddress != null) {
                        //如果此IP为IPV4 则返回
                        if (inetAddress instanceof Inet4Address && inetAddress.isReachable(1) && "en0".equals(networkInterface.getName())) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
            return getHostAddress();

        } catch (IOException e) {
            log.error("IpUtil getInet4Address error", e);
            return "";
        }
    }


    public static void main(String[] args) {
        System.out.println(getHostAddress());
        System.out.println(getInet4Address());
    }
}
